package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.TopicDetailGridAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.TopicDetail;
import com.elinkway.infinitemovies.bean.TopicDetailList;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.TopicDetailParser;
import com.elinkway.infinitemovies.listener.MyOnRefreshListner;
import com.elinkway.infinitemovies.push.PushStatsPoster;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.NoScrollGridView;
import com.handmark.pulltorefresh.library.BDReporter;
import com.handmark.pulltorefresh.library.HeaderView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.util.Map;
public class TopicDetailActivity extends BaseActionBarActivity implements HeaderView, BDReporter {

    public static final String TAG = "TopicDetailActivity";
    private PullToRefreshScrollView scrollView;
    private NoScrollGridView mGridView;
    private Bundle bundle;
    private TopicDetailGridAdapter mGridAdapter;

    //网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;

    private String themeid;
    private String title;
    private TopicDetailList topicList;
    private RequestTopicDetailListTask requestTask;
    private View loading;
    private ImageView mLoadingIv;
    private AnimationDrawable animationDrawable;
    private View loading_failed;
    private Button btnRefresh;
    private int currentPage = 1;
    private boolean hasMore = true;
    private ImageView mCover;
    private TextView mSubNameTv;
    private TextView mDesc;
    private RelativeLayout cover_img_container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        initActionBar();
        super.setActionBarActivityClassName(TAG);
        setContentView(R.layout.activity_topic_detail);
        bundle = getIntent().getExtras();
        JumpData jd = (JumpData) getIntent().getSerializableExtra(Utils.THEME_DATA);
        themeid = jd.getThemeid();
        currentPageId = BigDataConstants.PGV_CURRENT_ID_THEME + themeid;
        title = jd.getName();
        mTitleTv.setText(title);
        // 推送跳转友盟数据上报
        PushStatsPoster.postPushClickStats(bundle, UmengEventPoster.PUSH_TYPE_THEME);
//		initTitleBar();
        initGridView();
        initCover();
        initLoading();
        setOnLoading();
        requestTask = new RequestTopicDetailListTask(this, currentPage, true, true);
        requestTask.start();
        MoviesApplication.getInstance().setTopActivity(this);
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        mActionView.setBackgroundResource(R.drawable.home_title_bg_shape);
        mLeftBackIv.setImageResource(R.drawable.left_back_white_icon_selector);
        mTitleTv.setTextColor(getResources().getColor(R.color.white));
    }

    private void initCover() {
        cover_img_container = (RelativeLayout) findViewById(R.id.topic_detail_cover_img_container);
        mCover = (ImageView) findViewById(R.id.topic_detail_cover_img);
        mSubNameTv = (TextView) findViewById(R.id.sub_title_tv);
        mDesc = (TextView) findViewById(R.id.topic_detail_cover_text);
    }

    private void initGridView() {
        scrollView = (PullToRefreshScrollView) findViewById(R.id.topic_detail_scroll);
        mGridView = (NoScrollGridView) findViewById(R.id.topic_detail_grid);
        scrollView.setmBDReporter(this);
        scrollView.setOnRefreshListener(new TopicOnRefreshListener());
        scrollView.setmHeaderView(this);
        resetHasMore();
        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                String aid = topicList.getTopics().get(position).getAlbumId();
                String title = topicList.getTopics().get(position).getName();
                String vt = topicList.getTopics().get(position).getVideotype();
                MoviesApplication.getInstance().setLastPageClassName(TAG + "_" + TopicDetailActivity.this.title);
                RealDataApi.RealDataClickReport("","",aid,"","");

                Map<String, String> dataMap = BigDataApi.createDataMap("0", "", "0", "-", aid, "-");
                dataMap.put("rank", position + 1 + "");
                dataMap.put("cur_url", currentPageId);
                BigDataApi.bigDataCommonReport(dataMap, TopicDetailActivity.this);

                VideoDetailActivity.launch(TopicDetailActivity.this, aid, vt, title, "", themeid, "", "0","","");
            }
        });
    }

    public static void launch(Activity activity, String themeid, String title) {
        launch(activity, themeid, title, false);
    }

    public static void launch(Activity activity, String themeid, String title, boolean isfrompush) {
        Bundle b = new Bundle();
        JumpData jd = new JumpData();
        jd.setThemeid(themeid);
        jd.setName(title);
        b.putSerializable(Utils.THEME_DATA, jd);

        Context context = activity;
        if (context == null) {
            context = MoviesApplication.getInstance();
        }
        Intent intent = new Intent(context, TopicDetailActivity.class);
        intent.putExtras(b);
        intent.putExtra(MoviesApplication.START_FROM_NOTIFICATION, isfrompush);
        UmengEventPoster.postThemeClick(title);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private class RequestTopicDetailListTask extends MoviesHttpAsyncTask<TopicDetailList> {

        private int requestPage;
        private boolean isRefresh = true;
        private boolean needLoading = false;

        @Override
        public void netNull() {
            if (needLoading) {
                setLoadingFailed();
            } else {
                UIs.showToast(R.string.net_error);
                scrollView.onRefreshComplete();
            }
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            if (needLoading) {
                setLoadingFailed();
            } else {
                UIs.showToast(R.string.net_error);
                scrollView.onRefreshComplete();
            }
            super.netErr(updateId, errMsg);
        }

        public RequestTopicDetailListTask(Context context, int requestPage, boolean isRefresh, boolean needLoading) {
            super(context);
            this.requestPage = requestPage;
            this.isRefresh = isRefresh;
            this.needLoading = needLoading;
        }

        @Override
        public LVideoDataHull<TopicDetailList> doInBackground() {
            return MoviesHttpApi.requestTopicDetail(new TopicDetailParser(), requestPage, MoviesConstant.TOPIC_DETAIL_REQUEST_SIZE, themeid);
        }

        @Override
        public void onPostExecute(int updateId, TopicDetailList result) {
            setLoadingComplete();
            if (isRefresh) {
                currentPage = 1;
                topicList = result;
                mGridAdapter = new TopicDetailGridAdapter(TopicDetailActivity.this, topicList);
                mGridView.setAdapter(mGridAdapter);
                resetHasMore();
                setCover(result);
            } else {
                mGridAdapter.addItem_data(result);
            }
            if (result.getTopics().size() < MoviesConstant.TOPIC_DETAIL_REQUEST_SIZE) {
                setNoMore(requestPage);
            }
            currentPage++;
        }

    }

    private void initLoading() {
        loading = findViewById(R.id.topic_loading);
        mLoadingIv = (ImageView) findViewById(R.id.loading_progressBar);
        loading_failed = findViewById(R.id.topic_loading_failed);
    }

    public void setCover(TopicDetailList result) {
        String desc = result.getDesc();
        String subName = result.getSubName();
        if (!TextUtils.isEmpty(result.getPic())) {
            cover_img_container.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(result.getPic(), mCover);
        }
        if(!TextUtils.isEmpty(subName)){
            mSubNameTv.setText(subName);
            mSubNameTv.setVisibility(View.VISIBLE);
        }else{
            mSubNameTv.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(desc)) {
            mDesc.setText(desc);
        }
    }

    private void setLoadingFailed() {
        loading.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        mGridView.setVisibility(View.GONE);
        scrollView.setVisibility(View.GONE);
        loading_failed.setVisibility(View.VISIBLE);
        btnRefresh = (Button) loading_failed.findViewById(R.id.bn_refresh);
        btnRefresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (requestTask != null) {
                    requestTask.cancel();
                }
                requestTask = new RequestTopicDetailListTask(TopicDetailActivity.this, currentPage, true, true);
                requestTask.start();
                setOnLoading();
            }
        });
        scrollView.onRefreshComplete();
    }

    private void setOnLoading() {
        loading.setVisibility(View.VISIBLE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.start();
        scrollView.setVisibility(View.GONE);
        mGridView.setVisibility(View.GONE);
        loading_failed.setVisibility(View.GONE);
        scrollView.onRefreshComplete();
    }

    private void setLoadingComplete() {
        loading.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        scrollView.setVisibility(View.VISIBLE);
        mGridView.setVisibility(View.VISIBLE);
        loading_failed.setVisibility(View.GONE);
        scrollView.onRefreshComplete();
    }

    private class TopicOnRefreshListener extends MyOnRefreshListner {

        @Override
        public void onLoadMoreData() {
            if (hasMore) {
                if (requestTask != null) {
                    if (!requestTask.isCancelled()) {
                        requestTask.cancel();
                        requestTask = null;
                    }
                }
                requestTask = new RequestTopicDetailListTask(getApplicationContext(),
                        currentPage, false, false);
                requestTask.start();
            } else {
                scrollView.onRefreshComplete();
            }
        }

        @Override
        protected void onRefreshData() {
            currentPage = 1;
            if (requestTask != null) {
                if (!requestTask.isCancelled()) {
                    requestTask.cancel();
                    requestTask = null;
                }
            }
            requestTask = new RequestTopicDetailListTask(getApplicationContext(),
                    currentPage, true, false);
            requestTask.start();
        }

    }

    private void setNoMore(int requestPage) {
        hasMore = false;
        if (requestPage == 1) {
            scrollView.setMode(Mode.DISABLED);
        }
        scrollView.setLoadingDrawable(getResources().getDrawable(R.drawable.transparent), Mode.PULL_UP_TO_REFRESH);
        scrollView.setRefreshingLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
        scrollView.setReleaseLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
        scrollView.setPullLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
    }

    private void resetHasMore() {
        hasMore = true;
        scrollView.setMode(Mode.BOTH);
        scrollView.setLoadingDrawable(getResources().getDrawable(R.drawable.default_ptr_rotate), Mode.PULL_UP_TO_REFRESH);
        scrollView.setRefreshingLabel("加载中...", Mode.PULL_UP_TO_REFRESH);
        scrollView.setReleaseLabel("松开加载更多", Mode.PULL_UP_TO_REFRESH);
        scrollView.setPullLabel("上拉加载更多", Mode.PULL_UP_TO_REFRESH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        registerCheckNetwork();
    }


    /**
     * qinguoli
     * 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        intentfilter.addAction(Utils.SDCARD_NOSPACE_ACTION);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli
     * 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }


    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getAction().equals(PlayerUtils.CONNECTIVTY_CHANGE)) {
                    //读取保存的之前网络状态
                    SharedPreferences priorNetState = getSharedPreferences("priornetstate",
                            Activity.MODE_PRIVATE);

                    int priorNetType = priorNetState.getInt("netstate", 2);

                    int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);


                    SharedPreferences.Editor editor = priorNetState.edit();

                    editor.putInt("netstate", nowNetType);
                    editor.commit();
                }
                if (intent.getAction().equals(Utils.SDCARD_NOSPACE_ACTION)) {
                    DialogUtil.getInstance(TopicDetailActivity.this).checkSDCardSpaceDialog();
                }


            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterCheckNetwork();
    }

    @Override
    public void showFirstStatus() {
        mActionView.setBackgroundResource(R.drawable.home_title_bg_shape);
        mLeftBackIv.setImageResource(R.drawable.left_back_white_icon_selector);
        mTitleTv.setTextColor(getResources().getColor(R.color.white));
    }

    @Override
    public void showSecondStatus() {
        mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
        mLeftBackIv.setImageResource(R.drawable.left_back_icon_selector);
        mTitleTv.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void showGradientChange(int alpha) {
        if(alpha < 256 && alpha >= 0){
            mActionView.getBackground().setAlpha(alpha);
        }else{
            mActionView.getBackground().setAlpha(255);
        }
    }

    @Override
    public void bigDateShowReport(int y) {
        if(mGridView != null && mGridView.getCount() > 0 && mGridAdapter != null){
            int allHeight = scrollView.getHeight();
            float relativeTop = 0;
            com.apkfuns.logutils.LogUtils.d("ggg"+y);
            int size = mGridView.getCount();
            TopicDetail detail = null;
            for(int i=0; i<size; i++){
                detail = (TopicDetail) mGridAdapter.getItem(i);
                if(detail == null){
                    continue;
                }
                if(!detail.isInScreen()){
                    relativeTop = mGridView.getY() + mGridView.getChildAt(i).getY();
                    com.apkfuns.logutils.LogUtils.d("gggg"+mGridView.getY());
                    com.apkfuns.logutils.LogUtils.d("ggggg"+mGridView.getChildAt(i).getY());
                    com.apkfuns.logutils.LogUtils.d("gggggg"+relativeTop);
                    if(relativeTop <= 0){
                        continue;
                    }
                    if((y + allHeight > relativeTop) && (relativeTop > y)){
                        Map<String, String> dataMap = BigDataApi.createDataMap(BigDataConstants.ACODE_EXPOSURE, "","0","-",detail.getAlbumId(),"-");
                        dataMap.put("cur_url", currentPageId);
                        BigDataApi.bigDataCommonReport(dataMap, TopicDetailActivity.this);
                        ((TopicDetail) (mGridAdapter.getItem(i))).setInScreen(true);
                    }
                }
            }
        }
    }

    @Override
    public void dealWithUmeng() {
    }

    @Override
    public void dealWithVisitUmeng() {
        UmengEventPoster.postPageShow(UmengEventPoster.VISIT_TOPIC_DETAIL, title, MoviesApplication.getInstance().getLastPageClassName());
    }
}
